<?php
class MY_Model extends CI_Model{
	protected $dbname='';
	protected $insertFields='';
	protected $updateFields='';
	public function find($id){
		$this->db->from($this->dbname);
		$this->db->where('id',$id);
		return $this->db->get()->result('array')[0];
	}

	public function delete($id){
		if(method_exists($this, '_before_delete')){
			if($this->_before_delete($id)===FALSE){
				return false;
			}
		}
		$this->db->delete($this->dbname, array('id' => $id));
	}

	public function addData(){
		//构造数据
		$data=array();
		foreach ($this->insertFields as $v) {
			$data[$v]=$this->input->post($v,true);
		}
		/*添加前操作*/
		if(method_exists($this, '_before_insert')){
			if($this->_before_insert($data)===FALSE){
				return false;
			}
		}
		//插入数据库
		$ret=$this->db->insert($this->dbname,$data);
		//获取插入记录ID
		$data['id']=$this->db->insert_id();
		/*添加后操作*/
		if(method_exists($this, '_after_insert')){
			if($this->_after_insert($data)===FALSE){
				return false;
			}
		}
		return $data['id'];
	}

	public function updateData(){
		$id=$this->input->post('id');
		$this->db->where('id',$id);
		//构造数据
		$data=array();
		foreach ($this->updateFields as $v) {
			$data[$v]=$this->input->post($v,true);
		}
		/*修改前操作*/
		if(method_exists($this, '_before_update')){
			if($this->_before_insert($data)===FALSE){
				return false;
			}
		}
		//插入数据库
		$ret=$this->db->update($this->dbname,$data);
		/*修改后操作*/
		if(method_exists($this, '_after_update')){
			if($this->_after_update($data)===FALSE){
				return false;
			}
		}
		return $ret;
	}
}